import { Square } from "./Square";
import { IPoint } from "./Type";

export class SquareGroup {
  private _squares: readonly Square[] = [];

  constructor(
    private _shape: IPoint[],
    private _centerPoint: IPoint,
    private _color?: string
  ) {
    this._squares = this._shape.map((p) => {
      const sq = new Square();
      if (this._color) {
        sq.color = this._color;
      }
      return sq;
    });
    this.setSquareGroupShape();
  }

  public get centerPoint() {
    return this._centerPoint;
  }

  public set centerPoint(val) {
    this._centerPoint = val;
    this.setSquareGroupShape();
  }

  public get shape() {
    return this._shape;
  }

  public get squares() {
    return this._squares;
  }

  /**
   * 根据中心点与形状设置坐标
   */
  public setSquareGroupShape(): void {
    this._shape.forEach((p, i) => {
      this._squares[i].point = {
        x: p.x + this._centerPoint.x,
        y: p.y + this._centerPoint.y,
      };
    });
  }

  // 是否顺时针旋转
  protected _isClock = true;

  /**
   * 旋转后的形状
   */
  public afterRotateShape(): IPoint[] {
    if (this._isClock) {
      return this._shape.map((p) => ({
        x: -p.y,
        y: p.x,
      }));
    } else {
      return this._shape.map((p) => ({
        x: p.y,
        y: -p.x,
      }));
    }
  }

  /**
   * 旋转
   */
  public rotate(): void {
    const targetShape = this.afterRotateShape();
    this._shape = targetShape;
    this.setSquareGroupShape();
  }
}
